package me.idashu.attg.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import me.idashu.attg.domain.ContextEntity;
import me.idashu.attg.domain.ContributionEntity;
import me.idashu.attg.domain.PageEntity;
import me.idashu.attg.service.ContextService;
import me.idashu.attg.service.ContributionService;
import me.idashu.attg.util.Escape;
import me.idashu.attg.util.SystemConfig;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping("/context")
public class ContextController {

	@Autowired
	private ContextService contextService;

	@Autowired
	private SystemConfig systemConfig;

	@Autowired
	private ContributionService contributionService;

	@RequestMapping(value = "/addContext")
	public String addContext(Model model) {
		model.addAttribute("addContext", "添加内容板块");
		return "add_context";
	}

	@RequestMapping(value = "/addContextInfo")
	public String addContextInfo(
			Model model,
			@ModelAttribute ContextEntity contextEntity,
			@RequestParam(value = "file", required = false) MultipartFile[] files) {
		try {
			contextEntity.setTime(new Date());
			if (files != null && files.length > 0) {
				for (int i = 0; i < files.length; i++) {
					MultipartFile file = files[i];
					if (file.getOriginalFilename() != null
							&& !"".equals(file.getOriginalFilename())) {
						String imgurl = uploadImage(file);
						if (i == 0) {
							contextEntity.setIcon(imgurl);
						} else {
							contextEntity.setImgurl(imgurl);
						}
					}
				}
			}
			contextService.insertContext(contextEntity);
			model.addAttribute("success", "添加内容板块成功");
			return "success";
		} catch (Exception e) {
			e.printStackTrace();
			return "error";
		}
	}

	@RequestMapping(value = "/getContexts")
	public String getContexts(Model model,
			@ModelAttribute ContextEntity contextEntity,
			@ModelAttribute PageEntity pageEntity) {
		selectContextMethod(model, contextEntity, pageEntity);
		model.addAttribute("getContexts", "内容板块列表");
		return "contexts";
	}

	@RequestMapping(value = "/contextAjaxList")
	public String contextAjaxList(Model model,
			@ModelAttribute ContextEntity contextEntity,
			@ModelAttribute PageEntity pageEntity) {
		if (contextEntity.getTitle() != null
				&& !"".equals(contextEntity.getTitle())) {
			String title = Escape.unescape(contextEntity.getTitle());
			contextEntity.setTitle(title);
		}
		selectContextMethod(model, contextEntity, pageEntity);
		model.addAttribute("getContexts", "内容板块列表");
		return "contextsajax";
	}

	@RequestMapping(value = "/getOneContext")
	public String getOneContext(Model model,
			@ModelAttribute ContextEntity contextEntity) {
		ContextEntity context = contextService.findContextById(contextEntity
				.getId());
		model.addAttribute("context", context);
		return "contextinfo";
	}

	@RequestMapping(value = "/deleteContext")
	public String deleteContext(Model model,
			@ModelAttribute ContextEntity contextEntity) {
		contextService.deleteContexById(contextEntity.getId());
		PageEntity pageEntity = new PageEntity();
		selectContextMethod(model, contextEntity, pageEntity);
		return "contextsajax";
	}

	public void selectContextMethod(Model model, ContextEntity contextEntity,
			PageEntity pageEntity) {
		contextEntity.setSeq("mr");
		int count = contextService.findCountAllContexts(contextEntity);
		pageEntity.setTotalPage(count);
		pageEntity.setPageLess(pageEntity.getPage());
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("pageEntity", pageEntity);
		param.put("contextEntity", contextEntity);
		List<ContextEntity> contexts = contextService.findAllContexts(param);
		if (contexts != null && contexts.size() > 0) {
			model.addAttribute("contexts", contexts);
		} else {
			model.addAttribute("contexts", null);
		}
		model.addAttribute("pageEntity", pageEntity);
	}

	@RequestMapping(value = "/getContributions")
	public String setContribution(Model model,
			@ModelAttribute ContextEntity contextEntity,
			@ModelAttribute PageEntity pageEntity) {
		Map<String, Object> map = new HashMap<String, Object>();
		int count = contributionService
				.contributionCount(contextEntity.getId());
		pageEntity.setTotalPage(count);
		pageEntity.setPageLess(pageEntity.getPage());
		map.put("pageEntity", pageEntity);
		map.put("id", contextEntity.getId());
		List<ContributionEntity> contributions = contributionService.contributionsList(map);
		if(contributions == null ||contributions.size()==0){
			model.addAttribute("contributions", null);
		}else{
			model.addAttribute("contributions", contributions);
		}
		model.addAttribute("pageEntity", pageEntity);
		return "contributions";
	}
	
	@RequestMapping(value = "/setContribution")
	public String setContribution(Model model,
			@ModelAttribute ContextEntity contextEntity) {
		contextService.updateContextConId(contextEntity);
		model.addAttribute("success", "内容板块投稿设置成功！");
		return "success";
	}

	public String uploadImage(MultipartFile file) {
		String dir = systemConfig.getDir("dir");
		String prodir = systemConfig.getDir("prodir");
		String imgurl = null;
		try {
			InputStream is = file.getInputStream();
			byte[] inOutb = new byte[is.available()];
			String uuid = UUID.randomUUID().toString().replace("-", "");
			FileOutputStream fos = new FileOutputStream(new File(dir + uuid
					+ ".jpg"));
			imgurl = prodir + uuid + ".jpg";
			is.read(inOutb);
			fos.write(inOutb);
			is.close();
			fos.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return imgurl;
	}

}
